import React, { useEffect, useMemo } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import ShoppItem from "../../components/shoppItem";
import { NavBar, ActionBar, Notify } from "react-vant";
import { CartO, ChatO, ShopO, StarO, Star } from "@react-vant/icons";
import { useDispatch, useSelector } from "react-redux";
import { addToCart } from "../../store/modules/cart/cartActions";
import { stateToCart } from "../../utils";
import { addBrowerList, toggleCollectList } from "../../store/modules/user/userActions";
const Index = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const userCollectList = useSelector((state) => state.user.userCollectList);
  // 1. 获取路由发送过来的 state 参数
  const { pathname, state } = useLocation();
  // 获取购物车数据
  const allCount = useSelector((state) => state.cart.allCount);
  // 2. 加入购物车啊函数
  const handleAddToCart = () => {
    const payload = stateToCart(state);
    dispatch(addToCart(payload));
  };

  // 加入|取消收藏函数
  const handleAddCollect = () => {
    const token = localStorage.getItem("token");
    if (!token) {
      navigate("/login?from=" + pathname);
      return;
    }

    Notify.show({
      type: "success",
      message: isCollect ? "取消收藏成功" : "收藏成功",
    });
    dispatch(toggleCollectList(state));
  };
  // 是否shocking
  const isCollect = useMemo(() => {
    const item = userCollectList.find((v) => v.baseSpuId === state.baseSpuId);
    return item ? true : false;
  }, [userCollectList]);

  // 加入浏览记录
  const _addBrowerList = () => {
    dispatch(addBrowerList(state))
  }
  useEffect(() => {
    _addBrowerList()
  }, [])
  return (
    <div>
      <NavBar title="详情" onClickLeft={() => navigate(-1)} />
      <ShoppItem product={state}></ShoppItem>

      <ActionBar>
        <ActionBar.Icon
          icon={isCollect ? <Star color="red" /> : <StarO />}
          text={
            isCollect ? <span style={{ color: "red" }}>已收藏</span> : "收藏"
          }
          onClick={() => handleAddCollect()}
        />
        <ActionBar.Icon
          icon={<CartO />}
          text={"购物车"}
          badge={{ content: allCount ? allCount : "" }}
          onClick={() => navigate("/cart")}
        />
        <ActionBar.Button
          type="danger"
          text="立即购买"
          onClick={() => handleAddToCart()}
        />
      </ActionBar>
    </div>
  );
};

export default Index;
